<template>
  <view>
    <view class="category-page" :style="{top: navberHeight}">
      <cms-parse :identifier="identifier" @closeDefaultShow="closeDefaultShow"></cms-parse>
      <view class="cate-content u-bg-color">
        <view class="classify-title" :class="categoryFixed == 1 ? 'cate-title-fixed' : ''">
          <view class="title u-font-24">分类</view>
        </view>
        <!-- 一级分类列表 -->
        <view class="classify_catetory">
          <block v-for="(item, index) in rootcateList" :key="index">
            <view class="rootcate-view-item" :data-index="index" :data-navId="item.navId" :data-navType="item.navType"
              :data-urlPath="item.urlPath" :data-foreignId="item.foreignId" :data-navName="item.navName"
              :data-hasChild="item.parameters.hasChild" :data-hideSort="item.parameters.hideSort"
              :data-showFilter="item.parameters.showFilter" :data-isSpecial="item.parameters.isSpecial"
              :style="item.parameters.categoryColor" @click="hrefProductPosition(index,item)" v-if="item.visible">
              <image :class="categoryFixed == 0 ? 'showImage' : ''"
                :src="item.imageUrl ? item.imageUrl : 'https://efc-public-assets-1252208446.cos.ap-shanghai.myqcloud.com/images/1641792345900.jpg'">
              </image>
              <text class="navName"
                :class="[activeIndex == index ? 'navName-active' : '', categoryFixed == 1 ? 'navName-fixed': '']">{{ item.navName }}</text>
            </view>

          </block>
        </view>
      </view>
    </view>

    <!-- <view class="product-content u-bg-color" :style="productPaddingTop"> -->
    <view class="product-content u-bg-color">
      <view v-for="(rootcateitem, rootcateindex) in rootcateList" :key="rootcateindex" :id="'cateItem' + rootcateindex">
        <view class="catagoryNav" :id="'cateprocuct' +  rootcateindex">
          <view class="iconImg"
            style="background-image:url(https://100000063-1252208446.cos.ap-shanghai.myqcloud.com/images/miniprogram/%20images/category-bg.png)">
          </view>
          <view class="title">{{rootcateitem.navName}}</view>
          <block v-if="rootcateitem.parameters.isGtr">
            <view class="scroll-text">
              <text class="u-font-28 more">查看更多</text>
              <!-- <view class="macallan-icon mcl-youshuangjiantou"></view> -->
            </view>
          </block>
        </view>
        <block v-if="rootcateitem.parameters.drawlots">
          <cmsParse :identifier.sync="bannerId" :preview.sync="preview" @customEvent="onReportAbTest($event, rootcateitem.navName)"></cmsParse>
          <!-- <view class="macallan-icon mcl-youshuangjiantou"></view> -->
          <!-- <view class="scroll-text" @click="getMore()"><text class="u-font-24 more">查看更多</text></view> -->
        </block>
        <items :class="rootcateindex" :data-id="rootcateindex" ref="categoryItemRef"
          :categoryforeignId.sync="rootcateitem.foreignId" :categoryName.sync="rootcateitem.navName"
          :isSpecial.sync="rootcateitem.parameters.isSpecial" :isdrawlots.sync="rootcateitem.parameters.drawlots" :isGtr.sync="rootcateitem.parameters.isGtr">
        </items>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>

</template>

<script module="filterChecked" lang="wxs" src="@/utils/filter.wxs"></script>
<script>
  import api from '@/api/api';
  import {
    SYSTEM_INFO,
    SEL_CLASS_CODE,
    SEL_ACTIVE_CODE,
    MERCHANT_INFO,
    CUSTOMER_INFO,
    CART_KEY,
    LOWER_WX_VERSION
  } from '@/utils/constant';
  import items from './items.vue';
  import cmsParse from '../wxparse/wxparse.vue'
  import { reportEvent, getEventIdByNavName, EVENT_ID } from '@/utils/ab-test.js';

  export default {
    props: {
      categoryFixed: {
        type: Number,
        default: 0
      },
      isCateScroll: {
        type: Boolean,
        default: false
      },
      changeCate: {
        type: Number,
        default: 1
      },
    },
    components: {
      items,
      cmsParse,
    },

    data() {
      return {

        identifier: 'cms/cellartopbanner',
        showNotice: true,
        isIpx: false,
        nowPages: '',
        // 默认选中id
        activeIndex: 0,
        activeCode: 0,
        list: {},
        rootcateList: {}, //一级分类数据
        childcateList: {}, //子分类数据
        bannerId: 'cms/zhenxuanjianiang',
        preview: false
      };
    },
    
    watch: {
      rootcateList(rootcateList) {
        if (rootcateList.length) {
          this.$nextTick(() => {
            setTimeout(() => {
              const query = uni.createSelectorQuery().in(this);
              rootcateList.forEach((item, idx) => {
                const id = `#cateItem${idx}`
                query.select(id).boundingClientRect();
              })
              query.exec(res => {
                const cateDom = []
                res.forEach((cate, cateIdx) => {
                  if (cate) {
                    cateDom.push({...cate, index: cateIdx})
                  }
                })
                this.$emit("onCateLoaded", {cateDom})
              })
            }, 1000);
          })
        }
      }
    },

    mounted() {
      let that = this;
      let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
      this.isIpx = getApp().globalData.isIpx;
      let pages = getCurrentPages();
      var currPage = pages[pages.length - 1];
      this.nowPages = currPage.route;
    },

    computed: {
      navberHeight() {
        return getApp().globalData.navBarHeight + 'px';
      },

      productPaddingTop() {
        // return 'padding-top: calc(' + (this.categoryFixed ? 50 : 130 +  (this.showNotice ?  40 : 0)) + 'px' + ')';
      },

      cateScrollstate() {
        if (this.isCateScroll == false) {
          this.activeIndex = 0;
        }
      },
      changeCatestate() {
        this.activeIndex = this.changeCate;
      },
    },

    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      onReportAbTest(ev, navName) {
        reportEvent(EVENT_ID.CATEGORY.SHANG_CHENG);
        reportEvent(getEventIdByNavName(navName));
      },
      /**
       * 更新分类元素的高度
       */
      closeDefaultShow(val) {
        let that = this;
        this.showNotice = false;
      },
      pageScroll(object) {
        if (object.scrollTop >= 500) {
          this.activeIndex == 1
          this.$forceUpdate()
        }
        // let query = wx.createSelectorQuery()
        // query.select(’.nav’).boundingClientRect( (rect) => {
        // let top = rect.top
        // }).exec()
        // const query = uni.createSelectorQuery();
        // query.select('#cateItem0').boundingClientRect( (rect) => {
        // // let top = rect.top
        // }).exec()
        // this.$refs.categoryItemRef.pageScroll(object)
      },
      // 锚点跳转
      hrefProductPosition(e, item) {
        let index = e;
        if (index == 0 && this.isCateScroll == false) {
          return
        }
        if (this.activeIndex == index && this.activeIndex == 1) {
          return
        }

        this.activeIndex = e;

        // 锚点链接
        let id = '#cateprocuct' + index;
        const query = uni.createSelectorQuery().in(this);
        query.select(id).boundingClientRect();
        query.selectViewport().scrollOffset();
        query.exec(function(res) {
          uni.pageScrollTo({
            scrollTop: res[0].top + res[1].scrollTop - 270,
            duration: 500
          });
        });
        let clTrackPrams = {
          'c_firstlevel': item.navName,
          'c_secondlevel': ''
        }
        getApp().commonClTrack('c_ebmp_click_mall_mune', clTrackPrams)

      },


      changeCates(e) {
        let navtype = e.target.dataset.navtype || e.currentTarget.dataset.navtype, // 导航类型
          urlPath = e.target.dataset.urlpath || e.currentTarget.dataset.urlpath, // 分类跳转页面
          classId = e.target.dataset.foreignid || e.currentTarget.dataset.foreignid, // 分类id
          className = e.target.dataset.navname || e.currentTarget.dataset.navname, //分类名称
          hasChild = e.target.dataset.haschild || e.currentTarget.dataset.haschild || 1, // 是否显示子分类  1显示     0不显示
          isSort = e.target.dataset.hidesort || e.currentTarget.dataset.hidesort, // 是否显示排序    0显示     1不显示
          isFilter = e.target.dataset.showfilter || e.currentTarget.dataset.showfilter, // 是否显示筛选    0不显示   1显示
          isAppend = e.target.dataset.isspecial || e.currentTarget.dataset.isspecial, // 是否显示悬浮图  0不显示   1显示
          navId = e.target.dataset.navid || e.currentTarget.dataset.navid; // 导航id    用于调导航（二级分类）接口的参数

        //设置一级分类的选中状态
        this.activeIndex = e.currentTarget.dataset.index;
        if (hasChild == 0 || hasChild == '0') {
          if (navtype == 'link') {
            uni.navigateTo({
              url: '/pages/cms/page?identifier=' + urlPath + '&preview=false'
            });
          } else if (navtype == 'category') {
            //显示对应商品
            this.$emit('categoryChange', {
              cateCode: classId,
              title: className,
              hasChild: hasChild,
              navId: navId,
              isAppend: isAppend
            })
          }
        } else if (hasChild == 1) {
          if (navtype == 'link') {
            uni.navigateTo({
              url: '/pages/cms/page?identifier=' + urlPath + '&preview=false'
            });
          } else {
            this.getChildCate(navId);

            // 存储选中的一级分类
            let navSelectCode = [{
              'selClassCode': navId,
              'selActiveCode': this.activeIndex,
              'selMainNav': className
            }]

            uni.setStorageSync('SEL_CODE', navSelectCode)

          }

        }

      },

      jumpPage(e) {
        let that = this;
        let navtype = e.target.dataset.navtype, // 导航类型
          urlPath = e.target.dataset.urlpath, // 分类跳转页面
          classId = e.target.dataset.foreignid, // 分类id
          className = e.target.dataset.navname, //分类名称
          showChild = e.target.dataset.notshowchildren, // 是否显示子分类  0显示     1不显示
          isSort = e.target.dataset.hidesort, // 是否显示排序    0显示     1不显示
          isFilter = e.target.dataset.showfilter, // 是否显示筛选    0不显示   1显示
          isAppend = e.target.dataset.isspecial, // 是否显示悬浮图  0不显示   1显示
          navId = e.target.dataset.navid; // 导航id    用于调导航（三级分类）接口的参数
        if (navtype == 'category') {
          uni.vibrateShort({
            complete(res) {
              // uni.switchTab({
			  uni.relaunch({
                url: '/pages/category/category?cateCode=' +
                  classId +
                  '&title=' +
                  className +
                  '&showChild=' +
                  showChild +
                  '&isSort=' +
                  isSort +
                  '&isFilter=' +
                  isFilter +
                  '&isAppend=' +
                  isAppend +
                  '&navId=' +
                  navId
              });
            }
          });
        } else if (navtype == 'link') {
          uni.navigateTo({
            url: '/pages/cms/page?identifier=' + urlPath
          });
        } else {
          return;
        }
      },


      // 获取一级分类
      getRootCateTopLevel: async function(storeId) {
        let that = this;
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const json = await api.merchantNavigation({
          query: {
            parent_nav_id: 0,
            store_id: storeId
          }
        });
        if (json.code === 1000) {
          // 一级列表
          let firstCategory = json.data.content;
          let rootcategory = [];
          let rootNavigation = [];
          if (firstCategory.length > 0) {
            for (let i in firstCategory) {
              if (firstCategory[i].visible > 0 && firstCategory[i].foreignId !== 7957 && firstCategory[i].foreignId !== 8039 && firstCategory[i].foreignId !== 18457 && firstCategory[i].foreignId !== 18458) {
                rootcategory.push(firstCategory[i])
              }
            }
          }

          if (rootcategory.length > 0) {
            for (var i = 0; i < rootcategory.length; i++) {
              firstCategory.push(rootcategory[i].navId)
              if (rootcategory[i]['parameters']) {
                rootcategory[i].parameters = JSON.parse(rootcategory[i]['parameters']);
              } else {
                rootcategory[i].parameters = {};
              }

              if (rootcategory[i].parameters['categoryGroup'] !== null && rootcategory[i].parameters[
                  'categoryGroup'] !== undefined && rootcategory[i].parameters['categoryGroup'] > 0) {
                rootNavigation.push(rootcategory[i])
              } else {
                rootcategory[i].parameters['categoryGroup'] = "0";
                rootNavigation.push(rootcategory[i])
              }
            }

            rootNavigation.sort(function(a, b) {
              return a.parameters.categoryGroup - b.parameters.categoryGroup
            })

            if (rootNavigation.length > 0) {
              for (let j = 0; j < rootNavigation.length - 1; j++) {
                if (rootNavigation[j].parameters['categoryGroup'] != rootNavigation[j + 1].parameters[
                    'categoryGroup']) {
                  rootNavigation[j].select = true
                }
              }
            }
            this.rootcateList = rootNavigation;

            //显示一级分类的第一个分类对应商品
            // if(this.rootcateList[0].navType == "category" && this.rootcateList[0].parameters.hasChild == 0) {
            //   this.$emit('categoryChange', {
            //     cateCode: this.rootcateList[0].foreignId,
            //     title: this.rootcateList[0].navName,
            //     hasChild: this.rootcateList[0].parameters.hasChild,
            //     navId: this.rootcateList[0].navId,
            //     isAppend: this.rootcateList[0].parameters.isAppend
            //   })
            // }

            // let selCode = uni.getStorageSync('SEL_CODE');
            // if (selCode.length != 0 && firstCategory.indexOf(selCode[0].selClassCode) != -1) {
            //   this.activeCode = selCode[0].selClassCode;
            //   this.activeIndex = selCode[0].selActiveCode;
            //   this.getChildCate(this.activeCode,selCode[0].selMainNav);
            // } else {
            //   this.activeIndex = 0;
            //   this.childcateList = [];
            // }
          }
        } else {
          this.handleShowTextToast(json.msg);
        }
      },

      /*
       *    获取二级分类
       * */

      getChildCate: async function(rootCateCode) {
        let merchantInfo = uni.getStorageSync(MERCHANT_INFO);
        const json = await api.merchantNavigation({           method: 'GET',
          query: {
            parent_nav_id: rootCateCode,
            store_id: merchantInfo.cloudMerchantStoreId
          }
        });
        if (json.code === 1000) {
          // 二三级分类列表
          let category = json.data.content;
          let subNavigation = [];
          //解析每个数组下面的items.parameters属性
          for (let i = 0; i < category.length; i++) {
            // 解析字符串为数组
            if (category[i]['parameters']) {
              category[i].parameters = JSON.parse(category[i]['parameters']);
            }
            if (category[i].parameters['categoryGroup'] !== null && category[i].parameters['categoryGroup'] > 0) {
              subNavigation.push(category[i]);
            } else {
              category[i].parameters['categoryGroup'] = -1;
              subNavigation.push(category[i]);
            }
          }
          subNavigation.sort(function(a, b) {
            return a.parameters.categoryGroup - b.parameters.categoryGroup;
          });
          for (let j = 0; j < subNavigation.length - 1; j++) {
            if (subNavigation[j].parameters['categoryGroup'] != subNavigation[j + 1].parameters['categoryGroup']) {
              subNavigation[j].select = true;
            }
          }
          this.childcateList = subNavigation;
        } else {
          this.handleShowTextToast(json.msg);
        }
      },

    }
  };
</script>
<style lang="less" scoped>
  view {
    color: #999;
  }

  .category-page {
    width: 100%;
    position: fixed;
    z-index: 1000;
  }

  .cate-content {
    padding: 36rpx 32rpx;
    display: flex;
    position: relative;
    overflow: hidden;

    .classify-title {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      width: 140rpx;
      height: 150rpx;
      background-color: #efebe9;
      color: #1a1a1a;
      transition: all 0.4s;

      &.cate-title-fixed {
        height: 38rpx;
        border-right: 1px solid #000000;
        background-color: revert;
      }

      .title {
        color: #1a1a1a;
        font-weight: bold;
      }
    }


    .classify_catetory {
      width: 100%;
      display: flex;
      overflow-x: scroll;
      z-index: 1;

      .rootcate-view-item {
        padding-left: 10px;
        text-align: center;
        display: flex;
        flex-direction: column;
        align-items: center;

        image {
          width: 150rpx;
          height: 0rpx;
          opacity: 0;
          transition: all 0.4s;

          &.showImage {
            height: 150rpx;
            opacity: 1;
          }
        }

        .navName {
          display: block;
          text-align: center;
          line-height: 1.5;
        }

        .navName-active {
          color: #1a1a1a;
          font-weight: bold;
        }
      }
    }

    .navName-fixed {
      white-space: nowrap;
    }
  }

  .catagoryNav {
    display: flex;
    flex-direction: row;
    padding: 20rpx;
    margin-bottom: 4rpx;
    clear: both;
    align-items: flex-end;

    .title {
      color: #1a1a1a;
      font-size: 40rpx;
      line-height: 40rpx;
      margin-left: 14rpx
    }

    .iconImg {
      width: 32rpx;
      height: 50rpx;
      background-position: center;
      background-size: contain;
      background-repeat: no-repeat;
    }
  }

  .product-content {
    padding-top: 260rpx;
    // padding-top: 280rpx;
    // padding-top: 330rpx;
    // padding-bottom: 120rpx;
  }

  .scroll-text {
    display: flex;
    align-items: center;
    color: #000;
    position: absolute;
    right: 15px;
    .more {
      color: #000;
      margin-right: 5rpx;
      line-height: 30rpx;
      /* border-bottom: 1px solid #000; */
    }

    .macallan-icon {
      color: #000;
      font-size: 22rpx;
    }
  }

  .slide-up {
    animation-name: slideUp;
    animation-duration: 1s;
  }

  .side-down {
    animation-name: slideDown;
    animation-duration: 1s;
  }

  @keyframes slideUp {
    0% {
      height: 100%;
      opacity: 1;
    }

    100% {
      height: 0;
      opacity: 0;
    }
  }

  @keyframes slideDown {
    0% {
      height: 0;
      opacity: 0;
    }

    100% {
      height: 100%;
      opacity: 1;
      text-decoration: underline;
    }
  }
</style>
